package org.hd.userlist.controller;

import cn.dev33.satoken.util.SaResult;
import org.hd.userlist.service.UserListService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/userList/")
public class UserListController {

    @Resource
    UserListService userListService;


    @GetMapping ("getUserList")
    public SaResult getUserList(){
        List<Map<String, Object>> userList = userListService.getUSerList();
        Map<String,Object> result = new HashMap<>();
        result.put("roleList",userListService.getRoleList());
        result.put("userList",userList);

        if(null != userList){
            return new SaResult(200,"查询成功",result);
        }

        return SaResult.error("查询失败");
    }


    //修改用户状态
    @PostMapping("changeUserStatus")
    public SaResult changeUserStatus(
            @RequestBody Map<String,Object> map
    ){
        String username = (String) map.get("username");
        boolean flag = (Boolean)map.get("flag");
        boolean b = userListService.changeUserStatus(username, flag);
        if(b){
            return new SaResult(200,"设置成功",null);
        }
        return SaResult.error("设置失败");
    }

    @PostMapping("changeUserRole")
    public SaResult changeUserRole(
            @RequestBody Map<String,String> map
    ){
        String username = (String)map.get("username");
        String roleName =(String) map.get("roleName");
        if(userListService.changeUserRole(username,roleName)){
            return new SaResult(200,"用户角色修改成功",null);
        }
        return SaResult.error("修改用户角色失败，请联系站长");
    }

    @PostMapping("insertNewUser")
    public SaResult insertNewUser(
            @RequestBody Map<String,String> map
    ){
        String username = map.get("username");
        String password = map.get("password");
        String role = map.get("role");
        int resultInt = userListService.insertUser(username, password, role);
        if(resultInt == 1){
            return new SaResult(200,"新建用户成功",null);
        }else if(resultInt == 2){
            return SaResult.error("新建失败，请联系站长");
        }
        return SaResult.error("此用户与之前的用户重复了");
    }

    /**
     * 删除用户
     * @param
     * @return
     */
    @PostMapping("deleteUser")
    public SaResult deleteUser(
            @RequestBody Map<String,String> map
    ){
        String username = map.get("username");
        if(userListService.deleteUser(username)){
            return SaResult.ok("删除成功");
        }
        return SaResult.error("删除失败");
    }
}
